import React, { useState } from 'react';
import { Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import XLSX from 'xlsx';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const UploadFile: React.FC = (props) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const [fileContents, setFileContents] = useState<string[]>([]); // 存储文件内容

  const handleUpload = async () => {
    const formData = new FormData();

    fileList.forEach((file) => {
      formData.append('files[]', file as FileType);
    });

    setUploading(true);
    console.log(fileContents);
    // You can use any AJAX library you like
    axios
      .post(props.url ? props.url : '', fileContents)
      .then((res) => {
        console.log(res);
      })
      .then(() => {
        setFileList([]);
        setFileContents([]);
        message.success('upload successfully.');
      })
      .catch((error) => {
        message.error('upload failed.');
        console.log(error);
      })
      .finally(() => {
        setUploading(false);
      });
  };

  const props1: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target) {
          const content = e.target.result as string;
          setFileContents((prevContents) => [...prevContents, content]);
        }
      };
      reader.readAsText(file);

      setFileList([...fileList, file]);

      return false;
    },
    fileList,
  };

  return (
    <>
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Upload {...props1}>
          <Button icon={<UploadOutlined />}>{props.name}</Button>
        </Upload>
        <br />

        <Button
          type="primary"
          onClick={handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{ marginTop: 16 }}
        >
          {uploading ? 'Uploading' : 'Start Upload'}
        </Button>
      </div>

      <div>
        {/* {fileContents.map((content, index) => (
          <pre key={index}>{JSON.parse(JSON.stringify(content))}</pre>
        ))} */}
      </div>
    </>
  );
};

export default UploadFile;
